<template>
  <div class="messageConfigDetails h100">
    <editPageNew
      ref="editPage"
      :rightBtnArr="rightBtnArr"
      showTopTitle
      :creatInfo="formData"
    >
      <template slot="editPageTitle">
        消息配置
      </template>
      <el-collapse v-model="activeNames">
        <el-collapse-item name="1">
          <template slot="title">基本信息</template>
          <editForm :formConfig="editFormConfig" ref="basicForm" :formData="formData">
            <template #scope="{}">
              <el-form-item label="适用范围:">
                <el-checkbox style="float: left" :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                <br>
                <el-checkbox-group style="float: left" v-model="checkedDept" @change="handleCheckedDeptChange">
                  <el-checkbox v-for="(item,index) in deptList" :label="item.name" :key="index">{{item.name}}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </template>
            <template #message={}>
              <el-form-item label="消息模板:">
                <editTableM
                  :tableSetting="editTableSetting"
                  :tableData="tableData"
                  ref="editTable"
                  v-if="true"
                >
                </editTableM>
              </el-form-item>
            </template>
          </editForm>
        </el-collapse-item>
      </el-collapse>
    </editPageNew>
  </div>
</template>

<script>
import editTableM from './editTable.vue'
import {
  applicationQueryList
} from '@/api/systemManagement/applicationManagement.js'
import {
  queryMessageList,
  insertOrUpdateMessage, // 新增或修改
  queryByIdMessage, // 查询
  deleteByIdMessage, // 删除
} from "@/api/common.js"
export default {
  components: {
    editTableM
  },
  data(){
    return {
      formData: {},
      deptList: [],
      pageType: "",
      checkAll: false,
      checkedDept:[], //绑定默认选中
      checkedMark: [],
      isIndeterminate:false, //设置 indeterminate 状态，只负责样式控制
      activeNames: ["1"],
      tableData: [],
      editFormConfig: {
        itemArr: [
          {
            type: "text",
            label: "主题名称:",
            prop: "topicName",
            placeholder: "请输入主题名称",
            required: true,
            span: 12,
            clearable: true
          },
          {
            type: "text",
            label: "主题编码:",
            prop: "topicCode",
            placeholder: "请输入主题编码",
            required: true,
            span: 12,
            clearable: true,
            methods: obj=>{
              
            }
          },
          {
            label: "适用范围",
            prop: "scope",
            otherInfo: "checkbox",
            span: 24,
          },
          {
            label: "消息模板",
            prop: "message",
            otherInfo: "table",
            span: 24,
          },
          {
            type: "textarea",
            label: "备注",
            prop: "desc",
            methods: obj => {},
            span: 24,
            rows: 7,
            placeholder: "请输入",
          }
        ]
      },
      editTableSetting: {
        select: false,
        maxHeight: "100%",
        btnArr: [], 
        hideBtn: false,
        isShowIndex: false,
        buttonWidth: "100",
        editObj: {
          // 是否显示
          isShow: true,
          // 文字，文字图标可二选一，也可指定两者
          name: "",
          // 图标
          icon: "el-icon-edit"
        },
        buttonArr: [
          {
            name: '',
            icon: '',
            isShow: (row, index) => {
            },
            methods: (row,index)=>{
            }
          } 
        ],
        data: [],
        column: [
          {
            label: "通知方式",
            prop: "notifyType",
            width: 180,
            disabled: true,
            type: "select",
            seleteOption: this.$store.getters.dirtData("message_notify_type"),
            formatter: row => {
              let value = row;
              return (
                this.$store.getters["fineDirtDataName"](
                  "message_notify_type",
                  value
                ) || value
              );
            },
          },
          {
            label: "通知开关",
            prop: "status",
            type: "switch",
            activeText: "开",
            inactiveText: "关",
            width: 180,
            methods: (row,index)=>{
              console.log(row);
            },
            formatter: obj=>{
              if(obj==true){
                return "开";
              }else{
                return "关";
              }
            }
          },
          {
            label: "消息模板",
            prop: "template",
            type: "textarea",
            rows: 5,
            placeholder: "请输入"
          },
          {
            label: "说明",
            prop: "desc",
            type: "textarea",
            rows: 5,
            placeholder: "请输入"
          },
        ]
      }
    }
  },
  mounted(){
   
  },
  created(){
    this.pageType = this.$route.query.pageType;
    if(this.pageType != 'add'){
      this.formData.id = this.$route.query.id;
      this.getMessageDetails(this.formData.id);
    }else{
      let res = this.$store.getters.dirtData("message_notify_type");
      res.map(i=>{
        this.tableData.push({
          status: true,
          notifyType: i.value
        })
      })
    }
    applicationQueryList().then(res=>{
      this.deptList = res.data;
    })
  },
  methods: {
    handleCheckAllChange(val) {
      this.deptList.forEach(item=>{ 
        this.checkedDept.push(item.name);
        this.checkedMark.push(item.mark);
      })  
      this.checkedDept = val ? this.checkedDept : []; 
      this.isIndeterminate = false;  
    },
    handleCheckedDeptChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.deptList.length;  
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.deptList.length; 
    },
    // 保存
    async doSubmit(type){
      let scopeArr = [];
      this.deptList.map(i=>{
        this.checkedDept.map(j=>{
          if(j==i.name){
            scopeArr.push(i.mark);
          }
        })
      })
      let data = {};
      let scope = scopeArr.map((i) => i).join(",");
      let tableData = await this.$refs.editTable.getTableData();
      data.templatePoList = tableData;
      data.scope = scope;
      // 获取表单信息
      this.$refs.basicForm.getFormData().then(res=>{
        delete res.scope;
        delete res.templatePoList;
        data = Object.assign({},data,res);
        // 先校验主题编码是否重复
        insertOrUpdateMessage(data).then(res=>{
          this.formData = res.data;
          this.$utils.updateStorage();
          this.$message.success("操作成功！");
          if(this.pageType == 'add'){
            this.changeRouter();
          }else{
            this.getMessageDetails();
          }
        })
      }).catch(err=>{
        this.$message.warning(err);
      })
    },
    getMessageDetails(id){
      applicationQueryList().then(res1=>{
        this.deptList = res1.data;
        id = id || this.formData.id;
        queryByIdMessage(id).then(res=>{
          this.formData = res.data;
          // 处理适用范围
          let arr = res.data.scope.split(",");
          let scopeArr = [];
          this.deptList.map(i=>{
            arr.map(j=>{
              if(j==i.mark){
                scopeArr.push(i.name);
              }
            })
          })
          this.checkedDept = scopeArr;
          // 处理消息模板表格
          this.tableData = res.data.templatePoList;
        })
      })
    },
    // 删除
    deleteData(){
      let id = this.formData.id;
      deleteByIdMessage(id).then(res=>{
        this.$utils.updateStorage();
        this.$message.success("操作成功");
        this.$refs.editPage.closePage(1000);
      })
    },
    changeRouter() {
      /* 修改路由参数 */
      let obj = JSON.parse(JSON.stringify(this.$router.currentRoute.query));
      obj = Object.assign(obj, {
        id: this.formData.id,
        pageType: "edit",
      });
      this.$router.push({
        query: obj
      });
    },
  },
  computed: {
    rightBtnArr(){
      let arr = [
        {
          text: "保存",
          icon: "el-icon-check",
          methods: () => {
            this.doSubmit("save");
          }
        },
        {
          text: "删除",
          icon: "el-icon-delete",
          hide: ['add'].includes(this.pageType),
          methods: () => {
            this.deleteData();
          }
        }
      ];
      return arr;
    }
  }
}
</script>

<style lang="less" scoped>
  .messageConfigDetails{
    width: 100%;
    height: 100%;
    background-color: white;
  }
</style>